package com.swjd.jingle.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.swjd.jingle.R;
import com.swjd.jingle.activity.CaptureActivity;
import com.swjd.jingle.activity.MainActivity;
import com.swjd.jingle.util.App;
import com.swjd.jingle.util.Constant;
import com.swjd.jingle.util.DemoDataProvider;
import com.swjd.jingle.util.ScanUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.LoadingDialog;
import com.xuexiang.xui.widget.toast.XToast;

import java.lang.reflect.Constructor;

import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;

public abstract class BaseFragment extends Fragment {
    App app;//Application
    View view;//界面布局
    Unbinder unbinder;//绑定ButterKnife
    SharedPreferences sp;
    SharedPreferences.Editor editor;
    FragmentActivity activity;//上下文
    FragmentManager fragmentManager;//管理Fragment
    LoadingDialog dialog;//弹出提示框
    InputMethodManager imm;//弹出软键盘

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutId(), null);
        initAll();
        initialize();
        initViews();
        initData();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    /**
     * 为Fragment初始化必要的数据
     */
    private void initAll() {
        activity = getActivity();
        dialog = WidgetUtils.getLoadingDialog(activity)
                .setIconScale(0.4F)
                .setLoadingIcon(R.mipmap.ic_none)
                .setLoadingSpeed(8);
        unbinder = ButterKnife.bind(this, view);
        app = (App) activity.getApplication();
        sp = activity.getSharedPreferences("sp", MODE_PRIVATE);
        editor = sp.edit();
        fragmentManager = activity.getSupportFragmentManager();
        imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    /**
     * onCreate初始化
     */
    public abstract void initialize();

    /**
     * 初始化控件
     */
    public abstract void initViews();

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 初始化设置布局资源地址
     */
    public abstract int getLayoutId();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 下拉刷新
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    protected RefreshHeader getRefreshHeader(DemoDataProvider.Item item) {
        try {
            Class<?> headerClass = Class.forName("com.scwang.smartrefresh.header." + item.name());
            Constructor<?> constructor = headerClass.getConstructor(Context.class);
            return (RefreshHeader) constructor.newInstance(activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 获得运行时权限
    protected void getRuntimePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] perms = {Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (activity.checkSelfPermission(perms[0]) == PackageManager.PERMISSION_DENIED
                    || activity.checkSelfPermission(perms[1]) == PackageManager.PERMISSION_DENIED) {
                requestPermissions(perms, 200);
            } else {
                startActivityForResult(new Intent(activity, CaptureActivity.class), Constant.REQUEST_SCAN);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_SCAN) {
            if (resultCode == RESULT_OK) {
                XToast.success(activity, data.getStringExtra(ScanUtils.BAR_CODE), Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case 200: {
                for (int i : grantResults) {
                    if (i == PackageManager.PERMISSION_DENIED) {
                        XToast.error(activity, "权限被拒绝了！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                startActivityForResult(new Intent(activity, CaptureActivity.class), Constant.REQUEST_SCAN);
                break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (activity instanceof MainActivity) {
            ((MainActivity) activity).isAnimFlag();
        }
    }
}
